<template>
  <el-container class="layout-container">
    <!-- 顶部导航栏 -->
    <el-header class="navbar">
      <div class="navbar-left">
        <!-- 菜单折叠按钮 -->
        <el-button
          :icon="isCollapse ? Expand : Fold"
          @click="toggleCollapse"
          class="collapse-btn"
          text
        />
        <!-- Logo和标题 -->
        <div class="logo-container">
          <el-icon class="logo-icon"><Picture /></el-icon>
          <h1 class="logo-title">图片管理后台</h1>
        </div>
      </div>
      
      <div class="navbar-right">
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/" class="breadcrumb">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item v-if="route.meta.title">{{ route.meta.title }}</el-breadcrumb-item>
        </el-breadcrumb>
        
        <!-- 用户信息 -->
        <el-dropdown @command="handleCommand" class="user-dropdown">
          <div class="user-info">
            <el-avatar :size="32" class="user-avatar">
              {{ (authStore.username || '管理员').charAt(0) }}
            </el-avatar>
            <span class="username">{{ authStore.username || '管理员' }}</span>
            <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <el-icon><User /></el-icon>
                个人中心
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>
    
    <el-container>
      <!-- 移动端遮罩层 -->
      <div
        v-if="isMobile && !isCollapse"
        class="mobile-mask"
        @click="isCollapse = true"
      ></div>
      
      <!-- 侧边栏 -->
      <el-aside :width="asideWidth" class="aside" :class="{ 'mobile-show': !isCollapse && isMobile }">
        <el-menu
          :default-active="activeMenu"
          :collapse="isCollapse && !isMobile"
          :collapse-transition="false"
          router
          background-color="#304156"
          text-color="#bfcbd9"
          active-text-color="#409EFF"
          class="sidebar-menu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="/app-config">
            <el-icon><Setting /></el-icon>
            <template #title>应用配置</template>
          </el-menu-item>
          
          <el-menu-item index="/images">
            <el-icon><Picture /></el-icon>
            <template #title>图片管理</template>
          </el-menu-item>
          
          <el-menu-item index="/categories">
            <el-icon><Folder /></el-icon>
            <template #title>分类管理</template>
          </el-menu-item>
          
          <el-menu-item index="/users">
            <el-icon><User /></el-icon>
            <template #title>用户管理</template>
          </el-menu-item>
          
          <el-menu-item index="/favorites">
            <el-icon><Star /></el-icon>
            <template #title>收藏管理</template>
          </el-menu-item>
          
          <el-menu-item index="/history">
            <el-icon><Clock /></el-icon>
            <template #title>浏览历史</template>
          </el-menu-item>
          
          <el-menu-item index="/api-docs">
            <el-icon><Document /></el-icon>
            <template #title>API 文档</template>
          </el-menu-item>
        </el-menu>
      </el-aside>
      
      <!-- 主内容区 -->
      <el-main class="main">
        <router-view />
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessageBox } from 'element-plus'
import {
  Picture,
  Folder,
  Document,
  Setting,
  Star,
  Clock,
  User,
  Fold,
  Expand,
  ArrowDown,
  SwitchButton
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 菜单折叠状态
const isCollapse = ref(false)
const isMobile = ref(false)

// 侧边栏宽度
const asideWidth = computed(() => {
  if (isMobile.value) {
    // 移动端：折叠时宽度为0（通过transform隐藏），展开时200px
    return '200px'
  }
  // 桌面端：折叠时64px（只显示图标），展开时200px
  return isCollapse.value ? '64px' : '200px'
})

// 当前激活的菜单
const activeMenu = computed(() => route.path)

// 切换菜单折叠
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
  // 保存到 localStorage（仅在非移动端保存）
  if (!isMobile.value) {
    localStorage.setItem('menuCollapse', String(isCollapse.value))
  }
}

// 菜单选择处理（移动端选择后自动关闭）
const handleMenuSelect = () => {
  if (isMobile.value) {
    isCollapse.value = true
  }
}

// 检测屏幕尺寸
const checkMobile = () => {
  isMobile.value = window.innerWidth < 768
  if (isMobile.value) {
    isCollapse.value = true
  }
}

// 用户下拉菜单命令处理
const handleCommand = async (command) => {
  if (command === 'logout') {
    try {
      await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      authStore.logout()
      router.push('/login')
    } catch {
      // 用户取消
    }
  } else if (command === 'profile') {
    // 个人中心功能，后续可以扩展
    console.log('个人中心')
  }
}

// 初始化
onMounted(() => {
  // 从 localStorage 恢复折叠状态
  const savedCollapse = localStorage.getItem('menuCollapse')
  if (savedCollapse !== null) {
    isCollapse.value = savedCollapse === 'true'
  }
  
  // 检测屏幕尺寸
  checkMobile()
  window.addEventListener('resize', checkMobile)
})

onUnmounted(() => {
  window.removeEventListener('resize', checkMobile)
})
</script>

<style scoped>
.layout-container {
  height: 100vh;
  overflow: hidden;
}

/* 顶部导航栏 */
.navbar {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  position: relative;
  z-index: 1000;
}

.navbar-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.collapse-btn {
  font-size: 18px;
  color: #606266;
  padding: 8px;
}

.collapse-btn:hover {
  color: #409eff;
  background-color: #ecf5ff;
}

.logo-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.logo-icon {
  font-size: 24px;
  color: #409eff;
}

.logo-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
}

.navbar-right {
  display: flex;
  align-items: center;
  gap: 24px;
}

.breadcrumb {
  font-size: 14px;
}

/* 用户下拉菜单 */
.user-dropdown {
  cursor: pointer;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f7fa;
}

.user-avatar {
  background-color: #409eff;
  color: #fff;
  font-weight: 600;
}

.username {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.dropdown-icon {
  font-size: 12px;
  color: #909399;
  transition: transform 0.3s;
}

.user-dropdown:hover .dropdown-icon {
  transform: rotate(180deg);
}

/* 侧边栏 */
.aside {
  background-color: #304156;
  transition: width 0.3s;
  overflow: hidden;
}

.sidebar-menu {
  border-right: none;
  height: calc(100vh - 60px);
  overflow-y: auto;
  overflow-x: hidden;
}

.sidebar-menu:not(.el-menu--collapse) {
  width: 200px;
}

/* 主内容区 */
.main {
  background-color: #f0f2f5;
  padding: 20px;
  overflow-y: auto;
  height: calc(100vh - 60px);
}

/* 滚动条样式 */
.sidebar-menu::-webkit-scrollbar,
.main::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.sidebar-menu::-webkit-scrollbar-track,
.main::-webkit-scrollbar-track {
  background: transparent;
}

.sidebar-menu::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

.sidebar-menu::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}

.main::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

.main::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.3);
}

/* 移动端遮罩层 */
.mobile-mask {
  position: fixed;
  top: 60px;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 998;
  transition: opacity 0.3s;
}

/* 响应式 */
@media (max-width: 768px) {
  .navbar {
    padding: 0 12px;
  }
  
  .logo-title {
    font-size: 16px;
  }
  
  .breadcrumb {
    display: none;
  }
  
  .username {
    display: none;
  }
  
  .aside {
    position: fixed;
    left: 0;
    top: 60px;
    height: calc(100vh - 60px);
    z-index: 999;
    transition: transform 0.3s;
  }
  
  .aside:not(.mobile-show) {
    transform: translateX(-100%);
  }
  
  .aside.mobile-show {
    transform: translateX(0);
  }
}

/* Element Plus 菜单样式覆盖 */
:deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
}

:deep(.el-menu-item.is-active) {
  background-color: #1f2d3d !important;
}

:deep(.el-menu-item:hover) {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

:deep(.el-menu--collapse .el-menu-item) {
  padding: 0 20px !important;
}
</style>

